<template>
  <a-drawer
    v-if="open"
    title="编辑角色权限"
    :open="open"
    :maskClosable="false"
    :width="634"
    @close="onCancel"
  >
    <!-- loading -->
    <div v-if="init" class="float-left text-center mt-30">
      <a-spin />
    </div>

    <!-- 表单 -->
    <div v-show="!init" class="float-left mt-24">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        label-col="{ span: 5 }"
        wrapper-col="{ span: 19 }"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <!-- 角色名 -->
        <a-form-item label="角色名" name="name">
          <a-input
            v-model:value="formState.name"
            style="width: 424px"
            placeholder="请输入角色名"
            allow-clear
          />
        </a-form-item>

        <!-- 操作权限 -->
        <a-form-item label="操作权限" name="action_ids">
          <a-tree-select
            v-model:value="formState.action_ids"
            style="width: 424px"
            :tree-data="actions"
            tree-checkable
            allow-clear
            multiple
            placeholder="请选择权限"
            :list-height="600"
          />
        </a-form-item>

        <!-- 数据权限 -->
        <a-form-item label="数据权限" name="permission_ids">
          <a-tree-select
            v-model:value="formState.permission_ids"
            style="width: 424px"
            :tree-data="permissions"
            tree-checkable
            allow-clear
            multiple
            placeholder="请选择权限"
            :list-height="600"
          />
        </a-form-item>
      </a-form>
    </div>

    <!-- footer -->
    <template #footer>
      <a-space class="j-r-flex">
        <a-button @click="onCancel">取 消</a-button>
        <a-button type="primary" :loading="loading" @click="submitForm">
          确 认
        </a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { message } from "ant-design-vue";
import { adminRole } from "@/api/index";

interface PropInterface {
  id: any;
  open: boolean;
  onCancel: () => void;
}
interface Option {
  value: string | number;
  title: string;
  children?: Option[];
}

const props = defineProps<PropInterface>();
const { id, open, onCancel } = props;

// 状态
const init = ref(true);
const loading = ref(false);
const permissions = ref<Option[]>([]);
const actions = ref<Option[]>([]);

// 表单
const formRef = ref();
const formState = reactive({
  name: "",
  action_ids: [] as (string | number)[],
  permission_ids: [] as (string | number)[]
});

// 校验规则
const rules = {
  name: [{ required: true, message: "请输入角色名!" }]
};

// 监听 open/id
watch(
  () => props.open,
  (val) => {
    if (val) {
      getParams();
      if (id !== undefined) {
        init.value = true;
        getDetail();
      }
    }
  }
);

// 获取权限结构
const getParams = async () => {
  const res: any = await adminRole.createAdminRole();
  const arr: any = [];
  const arr2: any = [];
  const actionsRes = res.data.perm_action.action;
  const permissionsRes = res.data.perm_action.data;

  for (let i = 0; i < permissionsRes.length; i++) {
    const key = arr.findIndex((it: any) => it.title === permissionsRes[i].group_name);
    if (key >= 0) {
      arr[key].children.push({
        title: permissionsRes[i].name,
        value: permissionsRes[i].id
      });
    } else {
      arr.push({
        title: permissionsRes[i].group_name,
        value: permissionsRes[i].group_name + "-n",
        children: [{ title: permissionsRes[i].name, value: permissionsRes[i].id }]
      });
    }
  }

  for (let j = 0; j < actionsRes.length; j++) {
    const key = arr2.findIndex((it: any) => it.title === actionsRes[j].group_name);
    if (key >= 0) {
      arr2[key].children.push({
        title: actionsRes[j].name,
        value: actionsRes[j].id
      });
    } else {
      arr2.push({
        title: actionsRes[j].group_name,
        value: actionsRes[j].group_name + "-n",
        children: [{ title: actionsRes[j].name, value: actionsRes[j].id }]
      });
    }
  }

  permissions.value = arr;
  actions.value = arr2;
};

// 获取详情
const getDetail = async () => {
  const res: any = await adminRole.adminRole(id);
  const role = res.data.role;
  formState.name = role.name;
  formState.permission_ids = res.data.perm_data;
  formState.action_ids = res.data.perm_action;
  init.value = false;
};

// 提交表单
const onFinish = async (values: any) => {
  if (loading.value) return;
  let pids = values.permission_ids || [];
  let aids = values.action_ids || [];

  if (pids.length === 0 && aids.length === 0) {
    message.error("必须选择至少一个权限！");
    return;
  }

  loading.value = true;
  const params = aids.concat(pids);
  try {
    await adminRole.updateAdminRole(id, values.name, params);
    message.success("保存成功！");
    onCancel();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};

// 表单失败
const onFinishFailed = (errorInfo: any) => {
  console.log("Failed:", errorInfo);
};

// 提交方法
const submitForm = () => {
  formRef.value?.submit();
};
</script>
